import {
  migrateStorage,
  getFromStorage,
  saveToStorage,
} from "./scripts/storage.js";
import { scheduleHolidayRefresh } from "./scripts/services/holidays.js";
import { refreshRatesIfStale } from "./scripts/services/rates.js";

chrome.runtime.onInstalled.addListener(async (details) => {
  await migrateStorage();

  if (details.reason === "install") {
    chrome.alarms.create("refresh_rates", { periodInMinutes: 60 });
    chrome.alarms.create("refresh_holidays", { periodInMinutes: 60 * 24 });
  }
});

const ICON_DATA_URL =
  "";

chrome.alarms.onAlarm.addListener(async (alarm) => {
  if (alarm.name === "refresh_rates") {
    await refreshRatesIfStale(true);
  }
  if (alarm.name === "refresh_holidays") {
    await scheduleHolidayRefresh(true);
  }
  if (alarm.name.startsWith("reminder:")) {
    const id = alarm.name.slice("reminder:".length);
    const reminders = (await getFromStorage("reminders")) || [];
    const found = reminders.find((r) => r.id === id);
    if (found) {
      chrome.notifications.create({
        type: "basic",
        iconUrl: ICON_DATA_URL,
        title: found.title || "Reminder",
        message: found.message || "",
      });
      // Remove one-time reminder
      const next = reminders.filter((r) => r.id !== id);
      await saveToStorage("reminders", next);
    }
  }
});

chrome.runtime.onMessage.addListener((msg, _sender, sendResponse) => {
  if (msg?.type === "notify" && msg?.title) {
    chrome.notifications.create({
      type: "basic",
      iconUrl: ICON_DATA_URL,
      title: msg.title,
      message: msg.message || "",
    });
    sendResponse({ ok: true });
  }
  if (msg?.type === "scheduleReminder" && msg?.when) {
    (async () => {
      const id = Math.random().toString(36).slice(2);
      const name = `reminder:${id}`;
      const when = Number(msg.when);
      try {
        chrome.alarms.create(name, { when });
        const reminders = (await getFromStorage("reminders")) || [];
        reminders.push({ id, when, title: msg.title, message: msg.message });
        await saveToStorage("reminders", reminders);
        sendResponse({ ok: true, id });
      } catch (_e) {
        sendResponse({ ok: false });
      }
    })();
    return true; // async
  }
});

chrome.runtime.onStartup?.addListener(async () => {
  const reminders = (await getFromStorage("reminders")) || [];
  const now = Date.now();
  for (const r of reminders) {
    if (r.when > now) {
      chrome.alarms.create(`reminder:${r.id}`, { when: r.when });
    }
  }
});
